﻿using UnityEngine;
using System.Collections;

public class AspectHandler : MonoBehaviour {
	
	// set the desired aspect ratio (the values in this example are
	// hard-coded for 16:9, but you could make them into public
	// variables instead so you can set them at design time)
	private float targetAspect = 0.0f;

	void OnGUI() {	
		
		if(GUI.Button(new Rect(0, 0, 128, 128), "16:9")) {			
			
			ChangeAspect(16/9.0f);
		}
		
		if(GUI.Button(new Rect(128, 0, 128, 128), "4:3")) {			
			
			ChangeAspect(4/3.0f);
		}
		
		if(GUI.Button(new Rect(256, 0, 128, 128), "5:4")) {			
			
			ChangeAspect(5/4.0f);
		}
		
		if(GUI.Button(new Rect(384, 0, 128, 128), "3:2")) {			
			
			ChangeAspect(3/2.0f);
		}
		
		if(GUI.Button(new Rect(512, 0, 128, 128), "16:10")) {			
			
			ChangeAspect(16/10.0f);
		}
		
		if(GUI.Button(new Rect(640, 0, 128, 128), "Free aspect")) {			
			
			Rect freeAspect = new Rect(0.0f, 0.0f, 1.0f, 1.0f);
			camera.rect = freeAspect;
		}
	}
	
	void ChangeAspect(float aspect) {
		
		targetAspect = aspect;
		
		// determine the game window's current aspect ratio
		float windowaspect = (float)Screen.width / (float)Screen.height;
		
		// current viewport height should be scaled by this amount
		float scaleheight = windowaspect / targetAspect;
		
		// if scaled height is less than current height, add letterbox
		if (scaleheight < 1.0f)
		{  
			Rect rect = camera.rect;
			
			rect.width = 1.0f;
			rect.height = scaleheight;
			rect.x = 0;
			rect.y = (1.0f - scaleheight) / 2.0f;
			
			camera.rect = rect;
		}
		else // add pillarbox
		{
			float scalewidth = 1.0f / scaleheight;
			
			Rect rect = camera.rect;
			
			rect.width = scalewidth;
			rect.height = 1.0f;
			rect.x = (1.0f - scalewidth) / 2.0f;
			rect.y = 0;
			
			camera.rect = rect;
		}
		
	}
	
}
